<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getstoreList,
  addstore,
  updatestore,
  deletestore,
} from '#/api/core/store';
import type { VbenFormProps } from '@vben/common-ui';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { useVbenForm, z } from '#/adapter/form';
import { useVbenDrawer } from '@vben/common-ui';
import { ref } from 'vue';
import MapDialog from './mapdialog.vue';
import { useAccessStore } from '@vben/stores';

const [Drawer, drawerApi] = useVbenDrawer({
  title: '添加门店',
  footer: false,
});
const [Draweredit, drawereditApi] = useVbenDrawer({
  title: '编辑门店',
  footer: false,
});

interface RowType {
  category: string;
  color: string;
  id: string;
  price: string;
  productName: string;
  releaseDate: string;
}

const sleep = (time = 1000) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

/**
 * 获取示例表格数据
 */
async function getExampleTableApi(params: {
  storeName: any;
  page: any;
  size?: any;
}) {
  console.log(params);
  return new Promise<{ items: any; total: number }>(async (resolve) => {
    const { storeName, page, size } = params;
    const items = await getstoreList({
      storeName,
      page,
      size,
    });
    sleep(200).then(() => {
      resolve({
        total: items.data.total,
        items: items.data.list,
      });
    });
  });
}

const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  pagerConfig: {
    pageSizes: [2, 20, 50],
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { align: 'left', title: '店铺名称', field: 'store_name', width: 100 },
    {
      field: 'img',
      title: '店铺图片',
      slots: { default: 'img' },
    },
    { field: 'address', title: '店铺地址' },
    { field: 'ip', title: '店铺ip' },
    { field: 'StartWorking', title: '上班时间' },
    { field: 'endWorking', title: '下班时间' },
    { field: 'details', title: '门店详情' },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      width: 120,
    },
  ],
  exportConfig: {},
  // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await getExampleTableApi({
          page: page.currentPage,
          size: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '输入店铺名',
      },
      defaultValue: '',
      fieldName: 'storeName',
      label: '店铺名',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

function open() {
  fileListIcon.value = [];
  if (!formApi.state) return;
  formApi.state.type = 1;
  drawerApi.open();
}

let editData: any = ref({});
function openedit(data: any) {
  if (!formApi.state) return;
  // @ts-ignore
  formApi.state.type = 2;
  editData.value = data;
  editData.value.name = data.store_name;
  editData.value.image = data.img;
  editData.value.start_working = data.StartWorking;
  editData.value.end_working = data.endWorking;
  editData.value.id = data.id;
  formApi.setValues(editData.value);
  drawereditApi.open();
}

// 添加处理地图选择的方法
function handleMapAddress(address: any) {
  formApi.setValues({
    address: address.address,
    ip: `${address.longitude},${address.latitude}`, // 将经纬度组合作为 IP
  });
}

// 修改表单 schema，在原有的 schema 数组中添加地址相关字段
const [Form, formApi] = useVbenForm({
  //@ts-ignore
  type: 1,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入店铺名称',
      },
      fieldName: 'name',
      label: '店铺名称',
      rules: 'required',
    },

    {
      component: 'Upload',
      componentProps: {
        placeholder: '请上传店铺图片',
        listType: 'picture-card',
        limit: 1,
      },
      fieldName: 'image',
      label: '店铺图片',
    },
    {
      component: 'PrimaryButton',
      componentProps: {
        readonly: true,
        onClick: openMap,
        variant: 'primary',
        class: 'ipaddress',
      },
      fieldName: 'ipaddress',
      label: '选择位置',
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入店铺地址',
      },
      fieldName: 'address',
      label: '店铺地址',
      rules: 'required',
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '经纬度将自动填充',
        readonly: true,
      },
      fieldName: 'ip',
      label: '经纬度',
    },
    {
      component: 'VbenInput',
      componentProps: {
        type: 'time',
        placeholder: '请选择上班时间',
      },
      fieldName: 'start_working',
      label: '上班时间',
      rules: 'required',
    },
    {
      component: 'VbenInput',
      componentProps: {
        type: 'time',
        placeholder: '请选择下班时间',
      },
      fieldName: 'end_working',
      label: '下班时间',
      rules: 'required',
    },
    {
      component: 'VbenInput',
      componentProps: {
        type: 'textarea',
        placeholder: '请输入店铺详情',
      },
      fieldName: 'details',
      label: '店铺详情',
    },
  ],
  wrapperClass: 'grid-cols-1',
});

function onSubmit(values: Record<string, any>) {
  let url;
  let str;
  let api;
  //@ts-ignore
  if (formApi.state.type == 1) {
    url = addstore;
    str = '添加';
    api = drawerApi;
  } else {
    url = updatestore;
    //@ts-ignore
    values.id = editData.value.id;

    str = '修改';
    api = drawereditApi;
  }
  values.image = editData.value.image;
  url(values).then(() => {
    api.close();
    gridApi.query();
    ElMessage.success(str + '成功');
  });
}
const del = (data: { id: number }) => {
  ElMessageBox.confirm('此操作将永久删除该门店, 是否继续?', '提', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deletestore(data.id).then(() => {
      ElMessage.success('删除成功');
      gridApi.query();
    });
  });
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

// 添加地图组件的 ref
const mapDialogRef = ref();

// 在需要打开地图的地方调用
function openMap() {
  mapDialogRef.value?.show();
}
const fileListIcon = ref([]);
const changeIcon = (data: any) => {
  console.log(data);
  if (fileListIcon.value.length == 0) return;
  //@ts-ignore
  editData.value.image = data.data.url;

  fileListIcon.value = [];
};
const handleRemoveicon = () => {
  editData.value.image = '';
};
const beforeAvatarUploadicon = (rawFile: { type: string; size: number }) => {
  // icon只支持ico
  if (
    rawFile.type !== 'image/ico' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/jpg'
  ) {
    ElMessage.error('支持上传png，ico ,jpg，jpeg图像文件');
    return false;
    // icon大小不能超过10KB
  }
  // else if (rawFile.size / 1024 > 10) {
  //     ElMessage.error('图片不超过10KB')
  //     return false
  // }
  return true;
};
function formatToken(token: null | string) {
  return token ? `${token}` : null;
}

const accessStore = useAccessStore();
</script>

<template>
  <div class="vp-raw w-full">
    <Grid>
      <template #img="{ row }">
        <div style="padding: 10px 0">
          <img
            :src="row.img"
            alt=""
            v-if="row.img"
            style="width: 40px; height: 40px"
          />
        </div>
      </template>
      <template #action="{ row }">
        <el-button link type="primary" @click="openedit(row)">编辑</el-button>
        <el-button link type="danger" @click="del(row)">删除</el-button>
      </template>
      <template #toolbar-tools>
        <el-button class="mr-2" type="primary" @click="open">
          添加门店
        </el-button>
      </template>
    </Grid>

    <Drawer class="w-[800px]" ref="drawer"
      ><Form>
        <template #image="">
          <el-upload
            class="upload-demo"
            v-model:file-list="fileListIcon"
            drag
            :on-success="changeIcon"
            action="/v1/upload"
            :show-file-list="true"
            :on-remove="handleRemoveicon"
            :headers="{ authorization: formatToken(accessStore.accessToken) }"
            :before-upload="beforeAvatarUploadicon"
          >
            <img v-if="editData.image" :src="editData.image" class="avatar" />
            <el-icon class="el-icon--upload" v-else>
              <Plus />
            </el-icon>
          </el-upload>
        </template> </Form
    ></Drawer>
    <Draweredit class="w-[800px]" ref="draweredit"
      ><Form>
        <template #image="">
          <el-upload
            class="upload-demo"
            v-model:file-list="fileListIcon"
            drag
            :on-success="changeIcon"
            action="/v1/upload"
            :show-file-list="true"
            :on-remove="handleRemoveicon"
            :headers="{ authorization: formatToken(accessStore.accessToken) }"
            :before-upload="beforeAvatarUploadicon"
          >
            <img v-if="editData.image" :src="editData.image" class="avatar" />
            <el-icon class="el-icon--upload" v-else>
              <Plus />
            </el-icon>
          </el-upload>
        </template> </Form
    ></Draweredit>
    <MapDialog ref="mapDialogRef" @confirmMapAddress="handleMapAddress" />
  </div>
</template>
<style lang="scss">
.ipaddress {
  width: 100px;
  // 添加内容
  &::after {
    content: '选择位置';

    color: #fff;
  }
}

.avatar {
  width: 120px;
  height: 120px;
}
</style>
